import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { userInfoApi } from "@/axios/api/index";
import { useStore } from "@/store/user";
import loginVue from '@/views/login.vue'
import registerVue from "@/views/register.vue";
import { ElMessage } from "element-plus";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/index',  // 将根路径重定向到 /index
  },
  {
    path: '/login',
    name: 'login',
    component: loginVue
  },
  {
    path: '/register',
    name: 'register',
    component: registerVue,
  },
  {
    path: '/',
    name: 'home',
    component: () => import("../views/home.vue"),
    children: [
      {
        path: 'index',
        component: () => import("../views/index.vue")
      },
      {
        path: 'productsList',
        component: () => import("../views/products/productsList.vue"),
      },
      {
        path: 'addProducts',
        component: () => import("../views/products/addProducts.vue")
      },
      {
        path: 'updateProducts',
        component: () => import("../views/products/updateProducts.vue")
      },
    ]
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

/**
 * 路由守卫
 * 通过发请求，获取用户信息
 * 判断是否登录
 */
router.beforeEach((to, from, next) => {
  const store = useStore();
  const token = localStorage.getItem("token");

  if (!store.username && token) {
    userInfoApi().then(res => {
      if (res.code === 20002) {
        localStorage.removeItem("token");
        store.username = "";
        router.push("/login");
        // next("/login");
      }
      if (res.code === 20000) {
        store.username = res.data.userInfo.username;
      }
    });
  }
  if (!token && to.path !== '/login' && to.path !== '/register') {
    ElMessage.error("请先登录");
    next("/login");
  }
  next();
})

export default router
